package com.yanqu.road.server.manger.activity.winterLove;

import com.yanqu.road.entity.DataStatus;
import com.yanqu.road.entity.activity.ActivityConfig;
import com.yanqu.road.entity.activity.ActivityInfo;
import com.yanqu.road.entity.activity.winterLove.WinterLoveBagItem;
import com.yanqu.road.entity.activity.winterLove.WinterLoveUserData;
import com.yanqu.road.entity.activity.winterLove.config.WinterLoveComb;
import com.yanqu.road.entity.activity.winterLove.config.WinterLoveConfig;
import com.yanqu.road.entity.activity.winterLove.config.WinterLoveItem;
import com.yanqu.road.entity.enums.eActivityConfigType;
import com.yanqu.road.entity.enums.eActivityType;
import com.yanqu.road.entity.enums.eItemId;
import com.yanqu.road.logic.bussiness.activity.WinterLoveBusiness;
import com.yanqu.road.logic.config.GameConfig;
import com.yanqu.road.server.TempMgr;
import com.yanqu.road.server.gameplayer.GamePlayer;
import com.yanqu.road.server.gameplayer.module.activity.winterLove.WinterLoveModule;
import com.yanqu.road.server.manger.activity.ActivityMgr;
import com.yanqu.road.server.manger.activity.NormalActivityMgr;
import com.yanqu.road.server.manger.config.GoodsMgr;
import com.yanqu.road.server.manger.player.GamePlayerMgr;
import com.yanqu.road.utils.property.Property;
import com.yanqu.road.utils.property.PropertyHelper;
import com.yanqu.road.utils.string.StringUtils;

import java.math.BigInteger;
import java.util.*;

public class WinterLoveMgr extends TempMgr {


    private static WinterLoveConfig winterLoveConfig;

    public static WinterLoveConfig getWinterLoveConfig(){return winterLoveConfig;}

    public static ActivityInfo getActivityInfo(){
        return winterLoveConfig == null? null : winterLoveConfig.getActivityInfo();
    }

    @Override
    public boolean init() throws Exception {
        return reload();
    }

    @Override
    public boolean reload() throws Exception {
        return true;
    }

    @Override
    public boolean reloadConfig() throws Exception {
        return true;
    }

    @Override
    public boolean reloadData() throws Exception {
        return true;
    }

    @Override
    public boolean stop() {
        return false;
    }

    @Override
    public boolean save() {
        return true;
    }

    public static int getDisperseMaxTime(){
        return (winterLoveConfig.getDisperseGoldBlessLimit().get(2)-winterLoveConfig.getDisperseGoldBlessLimit().get(0))/winterLoveConfig.getDisperseGoldBlessLimit().get(1)+1;
    }

    /**
     * 活动结束发放没有兑换的奖励，从最好的comb兑换到最差的
     */
    public static Property autoSendReward(WinterLoveConfig config, WinterLoveUserData userData){
        Property reward = new Property();
        //依据稀有度level倒序取出comb表内容
        List<WinterLoveComb> winterLoveCombList = new ArrayList<>(config.getWinterLoveCombList());
        winterLoveCombList.sort(Comparator.comparing(WinterLoveComb::getLevel).reversed());
        //从大comb的开始遍历
        for (WinterLoveComb winterLoveComb:winterLoveCombList){
            List<String> rewardStringList = StringUtils.stringToStringList(winterLoveComb.getRewards(),";");
            int maxTime = checkCombEnoughTime(winterLoveComb,userData);     //找出最大组合值
            deductDecoration(winterLoveComb,userData,maxTime);              //减少用户的物品
            for (String rewardString:rewardStringList){
                //逐次加入奖励
                Property singleReward = PropertyHelper.parseStringToProperty(rewardString);
                for (int i=0;i<maxTime;i++){
                    reward.addProperty(singleReward);
                }
            }
        }
        return reward;
    }

    /**
     * 扣除最多可组成组合数的装饰物
     */
    private static void deductDecoration(WinterLoveComb comb,WinterLoveUserData winterLoveUserData,int maxNum){
        for (int needItemId:comb.getCombination()){
            WinterLoveBagItem haveItem= getBagItemById(needItemId,winterLoveUserData);
            haveItem.setDecorationNum(haveItem.getDecorationNum()-maxNum);
        }
        winterLoveUserData.setOp(DataStatus.Update);
    }

    /**
     * 查看该组合完成次数
     */
    private static int checkCombEnoughTime(WinterLoveComb comb,WinterLoveUserData winterLoveUserData){
        int maxNum=Integer.MAX_VALUE;
        for (int needItemId:comb.getCombination()){
            WinterLoveBagItem haveItem= getBagItemById(needItemId,winterLoveUserData);
            if (haveItem.getDecorationNum()<maxNum){
                maxNum=haveItem.getDecorationNum();
            }
        }
        return maxNum;
    }

    /**
     * 通过id获取背包中的物品
     */
    private static WinterLoveBagItem getBagItemById(int decorationId,WinterLoveUserData winterLoveUserData){
        for (WinterLoveBagItem haveItem:winterLoveUserData.getDecoration()){
            if (decorationId==haveItem.getDecorationId()){
                return haveItem;
            }
        }
        return null;
    }

    /**
     *获取送财奖励
     */
    public static Property getDisperseReward(BigInteger earnSpeed){
        BigInteger silver=earnSpeed.multiply(BigInteger.valueOf(winterLoveConfig.getDisperseGoldRewardTaelMinute()));
        String rewardString = winterLoveConfig.getDisperseGoldSock()+"="+1;
        Property rewardProperty = PropertyHelper.parseStringToProperty(rewardString);

        Property property = new Property();
        property.addProperty(GameConfig.GAME_MONEY_SILVER,silver);
        property.addProperty(rewardProperty);

        return property;
    }

    /**
     * 获取当前散财所需祝福
     */
    public static int getNowDisperseBlessLimit(int disperseTime){
        return winterLoveConfig.getDisperseGoldBlessLimit().get(0)+disperseTime*winterLoveConfig.getDisperseGoldBlessLimit().get(1);
    }

    /**
     * 获取单次挖雪奖励
     */
    public static int getScoreReward(){
        if(null==winterLoveConfig){
            return GoodsMgr.getGoodsById(eItemId.WINTERLOVE_SHOVE_ITEM_ID.getValue()).getParamList().get(0).intValue();
        }
        return GoodsMgr.getGoodsById(winterLoveConfig.getShovelItemId()).getParamList().get(0).intValue();
    }

    /**
     *用id取得装饰物
     */
    public static WinterLoveItem getItemById(int itemId,int level){
        List<WinterLoveItem> winterLoveItemList = level==1?winterLoveConfig.getWinterLoveLowItemList():winterLoveConfig.getWinterLoveHighItemList();
        for (WinterLoveItem winterLoveItem:winterLoveItemList){
            if (winterLoveItem.getItemId()==itemId){
                return winterLoveItem;
            }
        }
        return null;
    }

    /**
     * 数据库读配置
     */
    public static WinterLoveConfig loadWinterLoveConfigFromDb(ActivityInfo activityInfo){
        WinterLoveConfig tmpConfig = new WinterLoveConfig();
        tmpConfig.setActivityInfo(activityInfo);
        int tmpActivityId = tmpConfig.getActivityInfo().getActivityId();

        tmpConfig.setWinterLoveLowItemList(WinterLoveBusiness.getLowWinterLoveItemList(tmpActivityId));
        tmpConfig.setWinterLoveHighItemList(WinterLoveBusiness.getHighWinterLoveItemList(tmpActivityId));
        tmpConfig.setWinterLoveCombList(WinterLoveBusiness.getWinterLoveCombList(tmpActivityId));

        Map<String, ActivityConfig> activityConfigMap = NormalActivityMgr.getActivityConfigMap(tmpActivityId);
        tmpConfig.setBlessItemId(activityConfigMap.get(eActivityConfigType.WINTER_LOVESONG_ZHUFU_ITEM_ID.getName()).getIntValue());
        tmpConfig.setScoreItemId(activityConfigMap.get(eActivityConfigType.WINTER_LOVESONG_XUEHUA_ITEM_ID.getName()).getIntValue());
        tmpConfig.setShovelItemId(activityConfigMap.get(eActivityConfigType.WINTER_LOVESONG_XUECHAN_ITEM_ID.getName()).getIntValue());
        tmpConfig.setHighLevelCost(activityConfigMap.get(eActivityConfigType.WINTER_LOVESONG_HIGH_COST.getName()).getIntValue());
        tmpConfig.setHighLevelScoreMultiple(activityConfigMap.get(eActivityConfigType.WINTER_LOVESONG_HIGH_SCORENUM.getName()).getIntValue());
        tmpConfig.setHighLevelUnlockBlessNum(activityConfigMap.get(eActivityConfigType.WINTER_LOVESONG_HIGH_UNLOCK.getName()).getIntValue());
        tmpConfig.setMapMaxFullRate(activityConfigMap.get(eActivityConfigType.WINTER_LOVESONG_MAP_FULL_MAX.getName()).getIntValue());
        tmpConfig.setMapAnimalNum(activityConfigMap.get(eActivityConfigType.WINTER_LOVESONG_MAP_ANIMAL_NUM.getName()).getIntValue());
        tmpConfig.setDisperseGoldScoreLimit(activityConfigMap.get(eActivityConfigType.WINTER_LOVESONG_SONGCAI_LIMIT_SCORE.getName()).getIntValue());
        tmpConfig.setDisperseGoldBlessLimit(StringUtils.stringToIntegerList(activityConfigMap.get(eActivityConfigType.WINTER_LOVESONG_SONGCAI_LIMIT_ZHUFU.getName()).getValue(),"\\|"));
        tmpConfig.setDisperseGoldRewardTaelMinute(activityConfigMap.get(eActivityConfigType.WINTER_LOVESONG_SONGCAI_REWARD_YINLIANG.getName()).getIntValue());
        tmpConfig.setDisperseGoldSock(activityConfigMap.get(eActivityConfigType.WINTER_LOVESONG_SONGCAI_REWARD_WAZI.getName()).getIntValue());
        tmpConfig.setLowLevelBlessReward(StringUtils.stringToIntegerList(activityConfigMap.get(eActivityConfigType.WINTER_LOVESONG_CHENGJIU_REWARD_LOW.getName()).getValue(),";"));
        tmpConfig.setHighLevelBlessReward(StringUtils.stringToIntegerList(activityConfigMap.get(eActivityConfigType.WINTER_LOVESONG_CHENGJIU_REWARD_HIGHT.getName()).getValue(),";"));
        tmpConfig.setBeautyList(StringUtils.stringToIntegerList(activityConfigMap.get(eActivityConfigType.WINTER_LOVESONG_BEAUTY_LIST.getName()).getValue(),"\\|"));

        List<Integer> winterLoveHighWeightList = new ArrayList<>();
        List<Integer> winterLoveLowWeightList = new ArrayList<>();

        for (WinterLoveItem winterLoveItem:tmpConfig.getWinterLoveHighItemList()){
            winterLoveHighWeightList.add(winterLoveItem.getWeight());
        }
        for (WinterLoveItem winterLoveItem:tmpConfig.getWinterLoveLowItemList()){
            winterLoveLowWeightList.add(winterLoveItem.getWeight());
        }
        tmpConfig.setWinterLoveHighWeightList(winterLoveHighWeightList);
        tmpConfig.setWinterLoveLowWeightList(winterLoveLowWeightList);

        if (activityConfigMap.containsKey("MAIL_TITLE_COMBO_REWORD")) {
            tmpConfig.setMAIL_TITLE_COMBO_REWORD(activityConfigMap.get("MAIL_TITLE_COMBO_REWORD").getValue());
        }
        if (activityConfigMap.containsKey("MAIL_CONTENT_COMBO_REWORD")) {
            tmpConfig.setMAIL_CONTENT_COMBO_REWORD(activityConfigMap.get("MAIL_CONTENT_COMBO_REWORD").getValue());
        }
        if (activityConfigMap.containsKey("MAIL_TITLE_PROGRESS_REWORD")) {
            tmpConfig.setMAIL_TITLE_PROGRESS_REWORD(activityConfigMap.get("MAIL_TITLE_PROGRESS_REWORD").getValue());
        }
        if (activityConfigMap.containsKey("MAIL_CONTENT_PROGRESS_REWORD")) {
            tmpConfig.setMAIL_CONTENT_PROGRESS_REWORD(activityConfigMap.get("MAIL_CONTENT_PROGRESS_REWORD").getValue());
        }
        if (activityConfigMap.containsKey("MAIL_TITLE_DISPERSE_GOLD")) {
            tmpConfig.setMAIL_TITLE_DISPERSE_GOLD(activityConfigMap.get("MAIL_TITLE_DISPERSE_GOLD").getValue());
        }
        if (activityConfigMap.containsKey("MAIL_CONTENT_DISPERSE_GOLD")) {
            tmpConfig.setMAIL_CONTENT_DISPERSE_GOLD(activityConfigMap.get("MAIL_CONTENT_DISPERSE_GOLD").getValue());
        }

        return tmpConfig;
    }

    public static int getRandomBeautyId(){
        Random random = new Random();
        int num = random.nextInt(winterLoveConfig.getBeautyList().size());
        return winterLoveConfig.getBeautyList().get(num);
    }

    public static WinterLoveItem getBoxItem(int level){
        List<WinterLoveItem> winterLoveItemList = level==1?winterLoveConfig.getWinterLoveLowItemList():winterLoveConfig.getWinterLoveHighItemList();
        for (WinterLoveItem winterLoveItem:winterLoveItemList){
            if (winterLoveItem.getExtraId()!=0){
                return winterLoveItem;
            }
        }
        return null;
    }

    /**
     * 加载活动
     */
    public static void reloadActivityData(){
        getLogger().info("reload WinterLoveActivity start");

        //获取进行中的活动信息
        List<ActivityInfo> openActivityInfoList = NormalActivityMgr.getOpenActivityInfoList(eActivityType.WinterLoveActivity.getValue());
        if (openActivityInfoList.isEmpty()){
            getLogger().info("no WinterLoveActivity in show time");
            winterLoveConfig = null;
            return;
        }
        ActivityInfo activityInfo = openActivityInfoList.get(0);

        winterLoveConfig=loadWinterLoveConfigFromDb(activityInfo);

        getLogger().info("reload WinterLoveActivity finish");
        reloadPlayerData();
    }

    /**
     *  加载玩家活动数据
     */
    private static void reloadPlayerData(){
        if (ActivityMgr.activityInShowTime(winterLoveConfig.getActivityInfo())){
            for (GamePlayer player : GamePlayerMgr.getCopyPlayerMap().values()){
                WinterLoveModule module = player.getModule(WinterLoveModule.class);
                if (module != null) {
                    module.syncWinterLoveConfig();
                    module.initUserData();
                    module.syncUserData();
                }
            }
        }
    }

    public static int getShowTimeActivityId(){
        return getActivityInfo()==null ? 0:getActivityInfo().getActivityId();
    }

    public static boolean activityInTime(){
        return ActivityMgr.activityInTime(getActivityInfo());
    }

    public static void setWinterLoveConfig(WinterLoveConfig winterLoveConfig) {
        WinterLoveMgr.winterLoveConfig = winterLoveConfig;
    }
}
